<template>
  <div class="risk-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">风险管理</h1>
      <p class="page-description">项目风险识别、评估、应对和监控管理</p>
    </div>

    <!-- 风险概览卡片 -->
    <el-row :gutter="20" class="overview-cards">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon total">
              <el-icon><Warning /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ riskOverview.totalRisks }}</div>
              <div class="card-label">总风险数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon high">
              <el-icon><CircleCloseFilled /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ riskOverview.highRisks }}</div>
              <div class="card-label">高风险</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon medium">
              <el-icon><WarningFilled /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ riskOverview.mediumRisks }}</div>
              <div class="card-label">中风险</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon low">
              <el-icon><InfoFilled /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ riskOverview.lowRisks }}</div>
              <div class="card-label">低风险</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 风险分析图表 -->
    <el-row :gutter="20" class="charts-section">
      <el-col :xs="24" :lg="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>风险矩阵图</span>
              <el-select v-model="matrixProject" size="small" style="width: 150px">
                <el-option label="全部项目" value="all" />
                <el-option label="ERP系统开发" value="1" />
                <el-option label="移动端APP" value="2" />
              </el-select>
            </div>
          </template>
          <div ref="riskMatrixChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :lg="12">
        <el-card>
          <template #header>
            <span>风险趋势分析</span>
          </template>
          <div ref="riskTrendChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 风险列表管理 -->
    <el-card class="risk-list-section">
      <template #header>
        <div class="section-header">
          <span>风险列表</span>
          <div class="header-actions">
            <el-button type="primary" @click="showRiskDialog = true">
              <el-icon><Plus /></el-icon>
              新增风险
            </el-button>
            <el-button @click="exportRiskData">
              <el-icon><Download /></el-icon>
              导出数据
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索筛选 -->
      <div class="search-filters">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="8" :md="6">
            <el-input
              v-model="riskFilters.keyword"
              placeholder="搜索风险名称"
              clearable
              @input="handleRiskSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :xs="24" :sm="8" :md="6">
            <el-select v-model="riskFilters.level" placeholder="风险等级" clearable>
              <el-option label="高风险" value="high" />
              <el-option label="中风险" value="medium" />
              <el-option label="低风险" value="low" />
            </el-select>
          </el-col>
          <el-col :xs="24" :sm="8" :md="6">
            <el-select v-model="riskFilters.status" placeholder="风险状态" clearable>
              <el-option label="识别" value="identified" />
              <el-option label="评估" value="assessed" />
              <el-option label="应对" value="responding" />
              <el-option label="监控" value="monitoring" />
              <el-option label="关闭" value="closed" />
            </el-select>
          </el-col>
          <el-col :xs="24" :sm="24" :md="6">
            <el-button type="primary" @click="handleRiskSearch">搜索</el-button>
            <el-button @click="resetRiskFilters">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 风险表格 -->
      <el-table
        :data="filteredRiskList"
        v-loading="riskLoading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="name" label="风险名称" min-width="150" />
        <el-table-column prop="category" label="风险类别" width="100">
          <template #default="{ row }">
            <el-tag :type="getRiskCategoryType(row.category)">{{ getRiskCategoryLabel(row.category) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="probability" label="发生概率" width="100">
          <template #default="{ row }">
            <el-progress
              :percentage="row.probability"
              :color="getProbabilityColor(row.probability)"
              :stroke-width="8"
              text-inside
            />
          </template>
        </el-table-column>
        <el-table-column prop="impact" label="影响程度" width="100">
          <template #default="{ row }">
            <el-rate
              v-model="row.impact"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}"
            />
          </template>
        </el-table-column>
        <el-table-column prop="level" label="风险等级" width="100">
          <template #default="{ row }">
            <el-tag :type="getRiskLevelType(row.level)">{{ getRiskLevelLabel(row.level) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getRiskStatusType(row.status)">{{ getRiskStatusLabel(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="owner" label="负责人" width="100" />
        <el-table-column prop="identifiedDate" label="识别日期" width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="editRisk(row)">编辑</el-button>
            <el-button size="small" type="info" @click="viewRiskDetail(row)">详情</el-button>
            <el-button size="small" type="warning" @click="manageRiskResponse(row)">应对</el-button>
            <el-button size="small" type="danger" @click="deleteRisk(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="riskPagination.currentPage"
          v-model:page-size="riskPagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="riskPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleRiskSizeChange"
          @current-change="handleRiskCurrentChange"
        />
      </div>
    </el-card>

    <!-- 风险应对措施 -->
    <el-card class="response-section">
      <template #header>
        <span>风险应对措施</span>
      </template>
      
      <el-table
        :data="responseList"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="riskName" label="风险名称" width="150" />
        <el-table-column prop="strategy" label="应对策略" width="100">
          <template #default="{ row }">
            <el-tag :type="getStrategyType(row.strategy)">{{ getStrategyLabel(row.strategy) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="action" label="应对措施" min-width="200" />
        <el-table-column prop="responsible" label="负责人" width="100" />
        <el-table-column prop="deadline" label="完成期限" width="120" />
        <el-table-column prop="status" label="执行状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getResponseStatusType(row.status)">{{ getResponseStatusLabel(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="updateResponseStatus(row)">更新</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑风险对话框 -->
    <el-dialog
      v-model="showRiskDialog"
      :title="riskForm.id ? '编辑风险' : '新增风险'"
      width="700px"
      @close="resetRiskForm"
    >
      <el-form
        ref="riskFormRef"
        :model="riskForm"
        :rules="riskRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="风险名称" prop="name">
              <el-input v-model="riskForm.name" placeholder="请输入风险名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风险类别" prop="category">
              <el-select v-model="riskForm.category" placeholder="选择风险类别" style="width: 100%">
                <el-option label="技术风险" value="technical" />
                <el-option label="管理风险" value="management" />
                <el-option label="商业风险" value="business" />
                <el-option label="外部风险" value="external" />
                <el-option label="组织风险" value="organizational" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发生概率" prop="probability">
              <el-slider
                v-model="riskForm.probability"
                :min="0"
                :max="100"
                show-input
                :format-tooltip="formatProbability"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="影响程度" prop="impact">
              <el-rate
                v-model="riskForm.impact"
                :max="5"
                show-text
                :texts="['很低', '低', '中等', '高', '很高']"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="负责人" prop="owner">
              <el-select v-model="riskForm.owner" placeholder="选择负责人" style="width: 100%">
                <el-option
                  v-for="user in userList"
                  :key="user.id"
                  :label="user.name"
                  :value="user.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="识别日期" prop="identifiedDate">
              <el-date-picker
                v-model="riskForm.identifiedDate"
                type="date"
                placeholder="选择识别日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="风险描述">
          <el-input
            v-model="riskForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入风险描述"
          />
        </el-form-item>
        
        <el-form-item label="触发条件">
          <el-input
            v-model="riskForm.trigger"
            type="textarea"
            :rows="2"
            placeholder="请输入风险触发条件"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showRiskDialog = false">取消</el-button>
        <el-button type="primary" @click="saveRisk" :loading="riskSaving">保存</el-button>
      </template>
    </el-dialog>

    <!-- 风险应对对话框 -->
    <el-dialog
      v-model="showResponseDialog"
      title="风险应对管理"
      width="600px"
      @close="resetResponseForm"
    >
      <el-form
        ref="responseFormRef"
        :model="responseForm"
        :rules="responseRules"
        label-width="100px"
      >
        <el-form-item label="应对策略" prop="strategy">
          <el-select v-model="responseForm.strategy" placeholder="选择应对策略" style="width: 100%">
            <el-option label="规避" value="avoid" />
            <el-option label="减轻" value="mitigate" />
            <el-option label="转移" value="transfer" />
            <el-option label="接受" value="accept" />
          </el-select>
        </el-form-item>
        <el-form-item label="应对措施" prop="action">
          <el-input
            v-model="responseForm.action"
            type="textarea"
            :rows="3"
            placeholder="请输入具体的应对措施"
          />
        </el-form-item>
        <el-form-item label="负责人" prop="responsible">
          <el-select v-model="responseForm.responsible" placeholder="选择负责人" style="width: 100%">
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.name"
              :value="user.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="完成期限" prop="deadline">
          <el-date-picker
            v-model="responseForm.deadline"
            type="date"
            placeholder="选择完成期限"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="预算成本">
          <el-input-number
            v-model="responseForm.cost"
            :min="0"
            :precision="2"
            style="width: 100%"
            placeholder="请输入预算成本"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showResponseDialog = false">取消</el-button>
        <el-button type="primary" @click="saveResponse" :loading="responseSaving">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Warning,
  CircleCloseFilled,
  WarningFilled,
  InfoFilled,
  Plus,
  Download,
  Search
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 响应式数据
const riskOverview = ref({
  totalRisks: 24,
  highRisks: 3,
  mediumRisks: 8,
  lowRisks: 13
})

const matrixProject = ref('all')
const riskMatrixChart = ref()
const riskTrendChart = ref()

// 风险管理
const riskLoading = ref(false)
const showRiskDialog = ref(false)
const riskSaving = ref(false)
const riskFormRef = ref()

const riskFilters = reactive({
  keyword: '',
  level: '',
  status: ''
})

const riskPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const riskList = ref([
  {
    id: 1,
    name: '技术架构选型风险',
    category: 'technical',
    probability: 30,
    impact: 4,
    level: 'medium',
    status: 'assessed',
    owner: '张三',
    identifiedDate: '2024-01-15',
    description: '技术架构选型可能不适合项目需求',
    trigger: '技术评审发现架构问题'
  },
  {
    id: 2,
    name: '关键人员离职风险',
    category: 'organizational',
    probability: 20,
    impact: 5,
    level: 'high',
    status: 'responding',
    owner: '李四',
    identifiedDate: '2024-01-10',
    description: '核心开发人员可能离职',
    trigger: '人员流动性增加'
  },
  {
    id: 3,
    name: '需求变更频繁风险',
    category: 'management',
    probability: 60,
    impact: 3,
    level: 'medium',
    status: 'monitoring',
    owner: '王五',
    identifiedDate: '2024-01-08',
    description: '客户需求变更过于频繁',
    trigger: '需求变更超过预期次数'
  },
  {
    id: 4,
    name: '第三方服务依赖风险',
    category: 'external',
    probability: 15,
    impact: 4,
    level: 'low',
    status: 'identified',
    owner: '赵六',
    identifiedDate: '2024-01-05',
    description: '依赖的第三方服务可能不稳定',
    trigger: '第三方服务出现故障'
  }
])

const riskForm = reactive({
  id: null,
  name: '',
  category: '',
  probability: 50,
  impact: 3,
  owner: '',
  identifiedDate: '',
  description: '',
  trigger: ''
})

const riskRules = {
  name: [{ required: true, message: '请输入风险名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择风险类别', trigger: 'change' }],
  probability: [{ required: true, message: '请设置发生概率', trigger: 'blur' }],
  impact: [{ required: true, message: '请评估影响程度', trigger: 'change' }],
  owner: [{ required: true, message: '请选择负责人', trigger: 'change' }],
  identifiedDate: [{ required: true, message: '请选择识别日期', trigger: 'change' }]
}

// 风险应对
const showResponseDialog = ref(false)
const responseSaving = ref(false)
const responseFormRef = ref()
const currentRisk = ref(null)

const responseList = ref([
  {
    id: 1,
    riskId: 2,
    riskName: '关键人员离职风险',
    strategy: 'mitigate',
    action: '建立知识文档，培养备用人员，提高薪酬待遇',
    responsible: '李四',
    deadline: '2024-03-01',
    status: 'in_progress',
    cost: 50000
  },
  {
    id: 2,
    riskId: 3,
    riskName: '需求变更频繁风险',
    strategy: 'mitigate',
    action: '建立需求变更控制流程，设置变更审批机制',
    responsible: '王五',
    deadline: '2024-02-15',
    status: 'completed',
    cost: 10000
  }
])

const responseForm = reactive({
  strategy: '',
  action: '',
  responsible: '',
  deadline: '',
  cost: 0
})

const responseRules = {
  strategy: [{ required: true, message: '请选择应对策略', trigger: 'change' }],
  action: [{ required: true, message: '请输入应对措施', trigger: 'blur' }],
  responsible: [{ required: true, message: '请选择负责人', trigger: 'change' }],
  deadline: [{ required: true, message: '请选择完成期限', trigger: 'change' }]
}

// 用户列表
const userList = ref([
  { id: 1, name: '张三' },
  { id: 2, name: '李四' },
  { id: 3, name: '王五' },
  { id: 4, name: '赵六' }
])

// 计算属性
const filteredRiskList = computed(() => {
  let filtered = riskList.value
  
  if (riskFilters.keyword) {
    filtered = filtered.filter(item => 
      item.name.toLowerCase().includes(riskFilters.keyword.toLowerCase())
    )
  }
  
  if (riskFilters.level) {
    filtered = filtered.filter(item => item.level === riskFilters.level)
  }
  
  if (riskFilters.status) {
    filtered = filtered.filter(item => item.status === riskFilters.status)
  }
  
  riskPagination.total = filtered.length
  
  const start = (riskPagination.currentPage - 1) * riskPagination.pageSize
  const end = start + riskPagination.pageSize
  
  return filtered.slice(start, end)
})

// 方法
const getRiskCategoryType = (category: string) => {
  const types = {
    technical: 'primary',
    management: 'success',
    business: 'warning',
    external: 'danger',
    organizational: 'info'
  }
  return types[category] || 'default'
}

const getRiskCategoryLabel = (category: string) => {
  const labels = {
    technical: '技术风险',
    management: '管理风险',
    business: '商业风险',
    external: '外部风险',
    organizational: '组织风险'
  }
  return labels[category] || category
}

const getRiskLevelType = (level: string) => {
  const types = {
    high: 'danger',
    medium: 'warning',
    low: 'success'
  }
  return types[level] || 'default'
}

const getRiskLevelLabel = (level: string) => {
  const labels = {
    high: '高风险',
    medium: '中风险',
    low: '低风险'
  }
  return labels[level] || level
}

const getRiskStatusType = (status: string) => {
  const types = {
    identified: 'info',
    assessed: 'warning',
    responding: 'primary',
    monitoring: 'success',
    closed: 'default'
  }
  return types[status] || 'default'
}

const getRiskStatusLabel = (status: string) => {
  const labels = {
    identified: '识别',
    assessed: '评估',
    responding: '应对',
    monitoring: '监控',
    closed: '关闭'
  }
  return labels[status] || status
}

const getStrategyType = (strategy: string) => {
  const types = {
    avoid: 'danger',
    mitigate: 'warning',
    transfer: 'primary',
    accept: 'success'
  }
  return types[strategy] || 'default'
}

const getStrategyLabel = (strategy: string) => {
  const labels = {
    avoid: '规避',
    mitigate: '减轻',
    transfer: '转移',
    accept: '接受'
  }
  return labels[strategy] || strategy
}

const getResponseStatusType = (status: string) => {
  const types = {
    planned: 'info',
    in_progress: 'warning',
    completed: 'success',
    cancelled: 'danger'
  }
  return types[status] || 'default'
}

const getResponseStatusLabel = (status: string) => {
  const labels = {
    planned: '计划中',
    in_progress: '进行中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return labels[status] || status
}

const getProbabilityColor = (probability: number) => {
  if (probability >= 70) return '#f56c6c'
  if (probability >= 40) return '#e6a23c'
  return '#67c23a'
}

const formatProbability = (value: number) => {
  return `${value}%`
}

// 风险管理方法
const handleRiskSearch = () => {
  riskPagination.currentPage = 1
}

const resetRiskFilters = () => {
  riskFilters.keyword = ''
  riskFilters.level = ''
  riskFilters.status = ''
  riskPagination.currentPage = 1
}

const handleRiskSizeChange = (size: number) => {
  riskPagination.pageSize = size
  riskPagination.currentPage = 1
}

const handleRiskCurrentChange = (page: number) => {
  riskPagination.currentPage = page
}

const editRisk = (risk: any) => {
  Object.assign(riskForm, risk)
  showRiskDialog.value = true
}

const viewRiskDetail = (risk: any) => {
  ElMessage.info('查看风险详情功能开发中')
}

const manageRiskResponse = (risk: any) => {
  currentRisk.value = risk
  showResponseDialog.value = true
}

const deleteRisk = async (risk: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除风险"${risk.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = riskList.value.findIndex(item => item.id === risk.id)
    if (index > -1) {
      riskList.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  } catch {
    ElMessage.info('已取消删除')
  }
}

const saveRisk = async () => {
  if (!riskFormRef.value) return
  
  try {
    await riskFormRef.value.validate()
    riskSaving.value = true
    
    // 计算风险等级
    const riskScore = (riskForm.probability / 100) * riskForm.impact
    let level = 'low'
    if (riskScore >= 3) level = 'high'
    else if (riskScore >= 1.5) level = 'medium'
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (riskForm.id) {
      // 编辑
      const index = riskList.value.findIndex(item => item.id === riskForm.id)
      if (index > -1) {
        riskList.value[index] = { ...riskForm, level }
      }
      ElMessage.success('风险更新成功')
    } else {
      // 新增
      const newRisk = {
        ...riskForm,
        id: Date.now(),
        level,
        status: 'identified'
      }
      riskList.value.unshift(newRisk)
      ElMessage.success('风险创建成功')
    }
    
    showRiskDialog.value = false
    resetRiskForm()
  } catch (error) {
    console.error('保存风险失败:', error)
  } finally {
    riskSaving.value = false
  }
}

const resetRiskForm = () => {
  Object.assign(riskForm, {
    id: null,
    name: '',
    category: '',
    probability: 50,
    impact: 3,
    owner: '',
    identifiedDate: '',
    description: '',
    trigger: ''
  })
  if (riskFormRef.value) {
    riskFormRef.value.clearValidate()
  }
}

const exportRiskData = () => {
  ElMessage.success('风险数据导出功能开发中')
}

// 风险应对方法
const saveResponse = async () => {
  if (!responseFormRef.value) return
  
  try {
    await responseFormRef.value.validate()
    responseSaving.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const newResponse = {
      ...responseForm,
      id: Date.now(),
      riskId: currentRisk.value?.id,
      riskName: currentRisk.value?.name,
      status: 'planned'
    }
    
    responseList.value.unshift(newResponse)
    ElMessage.success('风险应对措施保存成功')
    
    showResponseDialog.value = false
    resetResponseForm()
  } catch (error) {
    console.error('保存风险应对措施失败:', error)
  } finally {
    responseSaving.value = false
  }
}

const resetResponseForm = () => {
  Object.assign(responseForm, {
    strategy: '',
    action: '',
    responsible: '',
    deadline: '',
    cost: 0
  })
  if (responseFormRef.value) {
    responseFormRef.value.clearValidate()
  }
}

const updateResponseStatus = (response: any) => {
  ElMessage.info('更新应对状态功能开发中')
}

// 图表初始化
const initRiskMatrixChart = () => {
  if (!riskMatrixChart.value) return
  
  const chart = echarts.init(riskMatrixChart.value)
  
  const data = riskList.value.map(risk => [
    risk.probability,
    risk.impact,
    risk.name,
    risk.level
  ])
  
  const option = {
    title: {
      text: '风险矩阵',
      left: 'center',
      textStyle: {
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: (params: any) => {
        const [probability, impact, name, level] = params.data
        return `${name}<br/>概率: ${probability}%<br/>影响: ${impact}<br/>等级: ${level}`
      }
    },
    grid: {
      left: '10%',
      right: '10%',
      bottom: '15%',
      top: '15%'
    },
    xAxis: {
      type: 'value',
      name: '发生概率 (%)',
      nameLocation: 'middle',
      nameGap: 30,
      min: 0,
      max: 100
    },
    yAxis: {
      type: 'value',
      name: '影响程度',
      nameLocation: 'middle',
      nameGap: 40,
      min: 1,
      max: 5
    },
    series: [
      {
        type: 'scatter',
        data: data,
        symbolSize: (data: any) => {
          const [probability, impact] = data
          return Math.sqrt(probability * impact) * 2
        },
        itemStyle: {
          color: (params: any) => {
            const level = params.data[3]
            const colors = {
              high: '#f56c6c',
              medium: '#e6a23c',
              low: '#67c23a'
            }
            return colors[level] || '#409EFF'
          }
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  // 响应式处理
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

const initRiskTrendChart = () => {
  if (!riskTrendChart.value) return
  
  const chart = echarts.init(riskTrendChart.value)
  
  const option = {
    title: {
      text: '风险趋势',
      left: 'center',
      textStyle: {
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['高风险', '中风险', '低风险'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '高风险',
        type: 'line',
        data: [5, 4, 3, 3, 2, 3],
        itemStyle: {
          color: '#f56c6c'
        }
      },
      {
        name: '中风险',
        type: 'line',
        data: [12, 10, 8, 9, 8, 8],
        itemStyle: {
          color: '#e6a23c'
        }
      },
      {
        name: '低风险',
        type: 'line',
        data: [15, 16, 14, 13, 15, 13],
        itemStyle: {
          color: '#67c23a'
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  // 响应式处理
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 生命周期
onMounted(() => {
  nextTick(() => {
    initRiskMatrixChart()
    initRiskTrendChart()
  })
})
</script>

<style scoped>
.risk-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-description {
  color: #909399;
  margin: 0;
  font-size: 14px;
}

/* 概览卡片样式 */
.overview-cards {
  margin-bottom: 24px;
}

.overview-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.overview-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
}

.card-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
  margin-right: 16px;
}

.card-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.card-icon.high {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.card-icon.medium {
  background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
}

.card-icon.low {
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
}

.card-info {
  flex: 1;
}

.card-value {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.card-label {
  font-size: 14px;
  color: #909399;
}

/* 图表区域样式 */
.charts-section {
  margin-bottom: 24px;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 风险列表和应对区域样式 */
.risk-list-section,
.response-section {
  margin-bottom: 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-filters {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fafafa;
  border-radius: 6px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .risk-management {
    padding: 12px;
  }
  
  .page-title {
    font-size: 20px;
  }
  
  .section-header {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .card-content {
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }
  
  .card-icon {
    margin-right: 0;
    width: 50px;
    height: 50px;
    font-size: 20px;
  }
  
  .card-value {
    font-size: 24px;
  }
  
  .chart-container {
    height: 250px;
  }
  
  .search-filters .el-row {
    flex-direction: column;
  }
  
  .search-filters .el-col {
    margin-bottom: 12px;
  }
}

@media (max-width: 480px) {
  .page-title {
    font-size: 18px;
  }
  
  .card-value {
    font-size: 20px;
  }
  
  .chart-container {
    height: 200px;
  }
  
  .header-actions {
    flex-direction: column;
  }
}
</style>